package top.dark.design.patterns.prototype.deepcopy;

import lombok.ToString;

import java.io.*;

/**
 * Author: Darkn
 * description:
 * Create Time: 2021/4/21 17:49
 */
@ToString
public class DeepProtoType implements Serializable, Cloneable {

    public String name;
    public DeepCloneableTarget deepCloneableTarget;

    public DeepProtoType() {
        super();
    }

    /**
     * 方式一：通过重写clone方法实现深拷贝
     */
    @Override
    protected Object clone() throws CloneNotSupportedException {
        Object deep = super.clone();
        DeepProtoType deepProtoType = (DeepProtoType) deep;
        deepProtoType.deepCloneableTarget = (DeepCloneableTarget) deepCloneableTarget.clone();
        return deepProtoType;
    }

    /**
     * 方式二：通过对象的序列化实现
     */
    public Object deepClone(){
        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;

        try (
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                ObjectOutputStream oos = new ObjectOutputStream(bos);
        ) {
            // 序列化
            oos.writeObject(this);

            // 反序列化
            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);
            DeepProtoType copyObject = (DeepProtoType) ois.readObject();
            return copyObject;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }finally {
            try {
                bis.close();
                ois.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
